package multi_thread;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class demo1 {
    //模拟线程池
//    1.核心线程、最大线程数-->管理策略
//    2.非核心线程最大空闲时间
//    3.任务队列BlockingQueue
//    4.submit方法提交任务

    //如果加入最大线程数
    static class MyThreadPool{
        public BlockingQueue<Runnable> queue=new ArrayBlockingQueue<>(1000);
        //private int coreNum=0;
        public MyThreadPool(int n) {
            for (int i = 0; i < n; i++) {
                Thread t=new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //此处逻辑？
                        while (true){
                            try {
                                Runnable runnable=queue.take();//线程被阻塞
                                runnable.run();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                });
                t.start();
                };
            }
            public void submit(Runnable runnable){
                try {
                    this.queue.put(runnable);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
    }
    public static void main(String[] args) {

        MyThreadPool myThreadPool=new MyThreadPool(10);

        for (int i = 0; i < 1000; i++) {//变量捕获
            int id=i;
            Runnable runnable=new Runnable() {
                @Override
                public void run() {
                    System.out.println(id+" "+Thread.currentThread().getName());
                }
            };
            myThreadPool.submit(runnable);
        }

    }
}
